package com.neo.tiny.middle.socket.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @Author: yqz
 * @CreateDate: 2022/8/19 20:12
 */
@Slf4j
@ServerEndpoint("/websocket/{msgId}")
@Component
public class WebSocketServer {

    private static final ConcurrentHashMap<String, Session> SESSION_MAP = new ConcurrentHashMap<>(16);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("msgId") String msgId) {
        log.info("创建连接");
        SESSION_MAP.put(msgId, session);
    }

    /**
     * 接收消息
     *
     * @param session
     * @param msgId
     */
    @OnMessage
    public void onMessage(Session session, String message, @PathParam("msgId") String msgId) {
        log.info("收到:{},的消息：{}", msgId, message);
        sendMessage(msgId, message + "！");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("msgId") String msgId) {
        log.info("关闭连接");
        SESSION_MAP.remove(msgId);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, @PathParam("msgId") String msgId, Throwable error) {
        SESSION_MAP.remove(msgId);
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public static void sendMessage(String msgId, String message) {
        Session session = SESSION_MAP.get(msgId);
        if (session == null) {
            return;
        }
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}